package com.handinglian.servicerecord.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.handinglian.common.dto.CommonPage;
import com.handinglian.common.utils.FastJsonUtil;
import com.handinglian.common.utils.StringUtil;
import com.handinglian.employee.dto.UserInfoDto;
import com.handinglian.employee.entity.UserInfo;
import com.handinglian.employee.service.UserInfoService;
import com.handinglian.servicerecord.dto.MessageDto;
import com.handinglian.servicerecord.dto.MessageIndexDto;
import com.handinglian.servicerecord.entity.MessageRecord;
import com.handinglian.servicerecord.mapper.MessageRecordMapper;
import com.handinglian.servicerecord.service.MessageService;
import com.handinglian.task.dto.TaskUserMessageDto;
import com.handinglian.task.param.MessageParam;
import com.handinglian.thirdparty.YunqixunApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageRecordMapper messageRecordMapper;
    @Autowired
    private YunqixunApiService yunqixunApiService;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public MessageDto get(Integer id) {
        return FastJsonUtil.ObjectToObject(messageRecordMapper.selectByPrimaryKey(id), MessageDto.class);
    }

    @Override
    public CommonPage<MessageDto> list(Integer userId, String userName, String customerNameOrPhone, String titleOrContent, String startDate, String endDate, String sortField, String sortOrder, Integer pageNum, Integer pageSize) {
        Date sDate = null;
        Date eDate = null;
        if (StrUtil.isNotBlank(startDate)&& StrUtil.isNotBlank(endDate)){
            sDate = DateUtil.parseDateTime(startDate);
            eDate = DateUtil.parseDate(endDate);
        }

        UserInfo userInfo = userInfoService.get(userId);
        List<Integer> userIds = null;
        if (!userInfo.getJobNum().equals("admin")){
            String dataList = userInfo.getDataList();
            List<Integer> departmentIds = StringUtil.stringToIntegerList(dataList);
            List<UserInfo> userInfos =  userInfoService.list(departmentIds);
            userIds = userInfos.stream().map(userInfo1 -> userInfo1.getUserId()).collect(Collectors.toList());
        }
        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;
        PageHelper.startPage(pageNum, pageSize);
        List<MessageRecord> messageRecords = messageRecordMapper.find(userIds, userName, customerNameOrPhone, titleOrContent, sDate, eDate, sortField, sortOrder);
        CommonPage<MessageDto> messageTemplates = CommonPage.restPage(messageRecords, MessageDto.class);
        return messageTemplates;
    }

    @Override
    public int sendSingleMessage(Integer userId, MessageParam messageParam) throws IOException {
        UserInfoDto userDto = userInfoService.loadUserInfo(userId);
        String content = messageParam.getContent();
        content = content.replaceAll("\\{客户称呼}",messageParam.getCustomerName());
        content = content.replaceAll("\\{客户经理姓名}", userDto.getUserName());
        content = content.replaceAll("\\{客户经理工号}", userDto.getJobNum());
        yunqixunApiService.singleSend(messageParam.getCustomerPhone(), content);

        MessageRecord messageRecord = convertToMessageRecord(userDto, messageParam);
        return create(messageRecord);
    }


    private MessageRecord convertToMessageRecord(UserInfoDto userDto, MessageParam messageParam) {
        MessageRecord messageRecord = new MessageRecord();
        messageRecord.setUserId(userDto.getUserId());
        messageRecord.setUserName(userDto.getUserName());
        messageRecord.setJobNum(userDto.getJobNum());
        messageRecord.setUserPhone(userDto.getMobilePhone());
        messageRecord.setCustomerName(messageParam.getCustomerName());
        messageRecord.setCustomerPhone(messageParam.getCustomerPhone());
        messageRecord.setTemplateTitle(messageParam.getTemplateTitle());
        messageRecord.setContent(messageParam.getContent());
        messageRecord.setCreateTime(new Date());
        messageRecord.setTaskUserId(messageParam.getTaskUserId());
        return messageRecord;
    }


    @Override
    @Transactional
    public int create(MessageRecord messageRecord) {
        return messageRecordMapper.insertSelective(messageRecord);
    }

    @Override
    @Async
    public Future<List<MessageIndexDto>> countMessageRecord(Date startDate, Date endDate) {
        return new AsyncResult<>(messageRecordMapper.countMessageRecord(startDate, endDate));
    }

    @Override
    public List<TaskUserMessageDto> list(Integer taskUserId) {
        return messageRecordMapper.findByTaskUserId(taskUserId);
    }
}
